package cn.iune.erp.accounting;

import java.sql.Connection;
import java.sql.Date;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.alibaba.fastjson.JSONObject;
import com.justep.baas.Utils;
import com.justep.baas.data.DataUtils;
import com.justep.baas.data.Table;
import com.justep.baas.data.Transform;

import cn.iune.common.base.BaseJPAImpl;



@Repository
public class AccountPeriodDaoJPAImpl extends BaseJPAImpl<AccountPeriod> implements IAccountPeriodDao {


	//	private final Logger log = LoggerFactory.getLogger(AccountPeriodDaoJPAImpl.class);

	private String kSql;
	
//	@PersistenceContext 
//	private EntityManager em ;

	@Override
	public void insert(AccountPeriod obj) {
		em.persist(obj);
	}

	@Override
	public void delete(String fID) {
		em.remove(em.getReference(AccountPeriod.class, fID));
	}

	@Override
	public AccountPeriod update(AccountPeriod obj) {
		AccountPeriod objNew = em.merge(obj);
		return objNew;
	}

	@Override
	public AccountPeriod getByID(String fID) {
		AccountPeriod singleResult = em.find(AccountPeriod.class, fID);
		return singleResult;
	}

	@Override
	public List<AccountPeriod> getAll() {
		kSql="SELECT AccountPeriod FROM AccountPeriod AccountPeriod ";
		Query query = em.createQuery(kSql);
		@SuppressWarnings("unchecked")
		List<AccountPeriod> resultList = query.getResultList();
		return resultList;
	}

	@Override
	public List<AccountPeriod> getByMasterID(String fMasterID) {
		// TODO Auto-generated method stub
		kSql="SELECT AccountPeriod FROM AccountPeriod AccountPeriod WHERE AccountPeriod.fMasterID=:fMasterID";
		Query query = em.createQuery(kSql);
		query.setParameter("fMasterID", fMasterID);
		@SuppressWarnings("unchecked")
		List<AccountPeriod> resultList = query.getResultList();
		return resultList;
	}

	@Override
	public AccountPeriod getByNo(String yearNo, String periodNo, String enterpriseNo) {
		//1、定义sql语句
		kSql="SELECT AccountPeriod FROM AccountPeriod AccountPeriod "
				+ " WHERE ( AccountPeriod.periodNo = :periodNo ) "
				+ " AND ( AccountPeriod.yearNo = :yearNo ) "
				+ " AND ( AccountPeriod.enterpriseNo = :enterpriseNo ) "
				;

		Query query = em.createQuery(kSql);
		query.setParameter("periodNo", periodNo);
		query.setParameter("yearNo", yearNo);
		query.setParameter("enterpriseNo", enterpriseNo);
		AccountPeriod singleResult = null;
		try{
			singleResult = (AccountPeriod) query.getSingleResult();
		}catch(NoResultException e){
			//捕获没有结果的异常
			//避免抛出异常而中断对前台的相应。
		}finally{
		}
		return singleResult;
	}

	@Override
	public AccountPeriod getByDate(Date orderDate, String enterpriseNo) {
		//1、定义sql语句
		kSql="SELECT AccountPeriod FROM AccountPeriod AccountPeriod "
				+ " WHERE  AccountPeriod.enterpriseNo = :enterpriseNo  "
				+ " AND  AccountPeriod.dateStart <= :orderDate  "
				+ " AND  AccountPeriod.dateEnd >= :orderDate  "
				;

		Query query = em.createQuery(kSql);
		query.setParameter("orderDate", orderDate);
		query.setParameter("enterpriseNo", enterpriseNo);
		AccountPeriod singleResult = null;
		try{
			singleResult = (AccountPeriod) query.getSingleResult();
		}catch(NoResultException e){
			//捕获没有结果的异常
			//避免抛出异常而中断对前台的相应。
		}finally{
			
		}
		return singleResult;
	}

	@Override
	public List<AccountPeriod> getPeriodNoList(String yearNo, String periodNoStart, String periodNoEnd, String enterpriseNo) {
		// TODO Auto-generated method stub
		kSql= " SELECT AccountPeriod as fID"
				+ " ,AccountPeriod.periodNo as periodNo " 
				+ " FROM AccountPeriod AccountPeriod " 
				+ " WHERE ( AccountPeriod.enterpriseNo = :enterpriseNo ) "
				+ " AND ( AccountPeriod.yearNo >= :yearNo ) "
				+ " AND ( AccountPeriod.periodNo >= :periodNoStart ) "
				+ " AND ( AccountPeriod.periodNo <= :periodNoEnd ) "
				+ " ORDER BY AccountPeriod.periodNo ASC"
				;
		Query query = em.createQuery(kSql);
		query.setParameter("yearNo", yearNo);
		query.setParameter("periodNoStart", periodNoStart);
		query.setParameter("periodNoEnd", periodNoEnd);
		query.setParameter("enterpriseNo", enterpriseNo);
		@SuppressWarnings("unchecked")
		List<AccountPeriod> resultList = query.getResultList();
		return resultList;
	}


	/*
	@Override
	public int save(JSONObject object) throws Throwable {
		// TODO Auto-generated method stub
		// JSON转换Table
		Table table = Transform.jsonToTable(object);
		List<Row> list = table.getRows();
		for(Row row : list){
			JSONObject javaObject= Transform.rowToJavaObject(table, row);
			AccountPeriod obj = JSON.toJavaObject(javaObject, AccountPeriod.class);
			System.out.println(JSON.toJSONString(javaObject));
			if(RowState.NEW.equals(obj.getRowState())){
				this.insert(obj);
			}
			if(RowState.EDIT.equals(obj.getRowState())){
				this.update(obj);
			}
			if(RowState.DELETE.equals(obj.getRowState())){
				this.delete(obj.getfID());
			}
		}
		return 0;
	}
	*/

	
	@Override
	public JSONObject create(JSONObject data) {
		//缺省列
		String defColstr = Utils.getDefCols(AccountPeriod.class);
		data.put("defColstr", defColstr);
		return Utils.newData(data);

	}
	

	@Override
	public JSONObject query(JSONObject data) throws SQLException{
		
		// 获取参数
		JSONObject columns = data.getJSONObject("columns"); // 列定义
		String orderBy = data.getString("orderBy"); // 排序
		Integer limit = data.getInteger("limit"); // 分页查询的行数
		Integer offset = data.getInteger("offset"); // 分页查询的行偏移
		String search = data.getString("search"); // 检索关键字
		String filter = data.getString("filter"); // 过滤条件
		String id = data.getString("id");
		String fMasterID = data.getString("fMasterID");
//		log.info("limit-->"+limit);
//		log.info("offset-->"+offset);
//		log.info("filters-->"+filters);
//		log.info("sqlParams-->"+params);
		/*
		limit-->15
		offset-->0
		filters-->[unitCode LIKE ? OR unitName LIKE ? OR unitType LIKE ?]
		sqlParams-->[%3%, %3%, %3%]
		*/		
		
		String format = "SELECT %s FROM %s %s %s ";
//		String format = "SELECT AccountPeriod FROM AccountPeriod AccountPeriod %s %s ";
		String select = "AccountPeriod.*"
//				+ ",FileItem.itemName"
//				+ ",FileItem.itemProperty"
//				+ ",FileItem.qualityType"
//				+ ",FileItem.qualityTypeLabel"
				;
		String from = "AccountPeriod AccountPeriod";
//		String from = "AccountPeriod AccountPeriod LEFT JOIN FileItem FileItem ON (FileItem.fID = AccountPeriod.itemID)";
		
		String where = "";

		
		// 存放SQL中的参数值
		List<Object> sqlParams = new ArrayList<Object>();
		// 存放SQL中的过滤条件
		List<String> filters = new ArrayList<String>();
		
		if (Utils.isNotEmptyString(search)) {
			// 增加过滤条件
			filters.add("peroidNo LIKE ? OR comments LIKE ? ");
			// 检索关键字中如果没有%，则前后自动加%
			search = (search.indexOf("%") != -1) ? search : "%" + search + "%";
			// sqlParams的参数个数和顺序必须与过滤条件的?相匹配 
			for (int i = 0; i < 2; i++) {
				sqlParams.add(search);
			}
		}
		
		//处理过滤条件
		if (Utils.isNotEmptyString(filter)) {
			filters.add(filter);
		}
		//处理id
		if (Utils.isNotEmptyString(id)) {
			filters.add("fID='"+id+"'");
		}
		//处理fMasterID
//		System.out.println("fMasterID-->"+fMasterID);
		if (Utils.isNotEmptyString(fMasterID)) {
			filters.add("fMasterID='"+fMasterID+"'");
		}
	
		
		if(filters != null && filters.size() > 0){
			if(where.indexOf("WHERE")== -1){
				//不包含WHERE关键字
				where = "WHERE " + DataUtils.arrayJoin(filters.toArray(), "(%s)", " AND ");
			}else{
				//已包含
				where = where + " AND " + DataUtils.arrayJoin(filters.toArray(), "(%s)", " AND ");
			}
		}
		//orderBy = "sortNo ASC";
//		String where = (filters != null && filters.size() > 0) ? " WHERE " + CommonService.arrayJoin(filters.toArray(), "(%s)", " AND ") : "";
		orderBy = Utils.isNotEmptyString(orderBy) ? " ORDER BY " + orderBy : "";
		
		String sql = String.format(format, select, from, where, orderBy);
		
//		Connection conn = DataUtils.getConnection(DataUtils.DATASOURCE_1);
		Connection conn = super.getConnection();
		String sqlTotal = String.format(format, "COUNT(*)", from, where, "");
		Object total = DataUtils.getValueBySQL(conn, sqlTotal, sqlParams);
		//SELECT AccountPeriod.fID FROM AccountPeriod AccountPeriod    LIMIT 0,-1//为-1时报错。
		if(limit==-1){
			limit = Integer.parseInt(total.toString());
		}
		
//		Table table = DataUtils.queryData(conn, tableName, columns, filters, orderBy, params, offset, limit);
		Table table = DataUtils.queryData(conn, sql, sqlParams, columns, offset, limit);
		//关闭连接
		conn.close();

		table.setTotal(Integer.parseInt(total.toString()));
		JSONObject json = Transform.tableToJson(table);
		return json;
	}


	
}
